package cn.stylefeng.guns.sys.modular.auth.controller;

import cn.hutool.core.lang.Dict;
import cn.stylefeng.guns.core.context.constant.ConstantContextHolder;
import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.pojo.response.ErrorResponseData;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.core.pojo.response.SuccessResponseData;
import cn.stylefeng.guns.sys.modular.auth.service.AuthService;
import cn.stylefeng.guns.sys.util.DESUtil;
import cn.stylefeng.guns.sys.util.RSAUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.security.PrivateKey;
import java.util.Map;

/**
 * 登录控制器
 *
 * @author xuyuxiang
 * @date 2020/3/11 12:20
 */
@RestController
@Slf4j
public class SysLoginController {

    @Resource
    private AuthService authService;


//    @Value("${auth.RSA.privateKeyStr}")
//    private String privateKeyStr;

    /**
     * 获取是否开启租户的标识
     *
     * @author fengshuonan
     * @date 2020/9/4
     */
    @GetMapping("/getTenantOpen")
    public ResponseData getTenantOpen() {
        return new SuccessResponseData(ConstantContextHolder.getTenantOpenFlag());
    }

    /**
     * 账号密码登录
     *
     * @author xuyuxiang
     * @date 2020/3/11 15:52
     */
    @PostMapping("/login")
    public ResponseData login(@RequestBody Dict dict) {
        String account = dict.getStr("account");
        String password = dict.getStr("password");
        String tenantCode = dict.getStr("tenantCode");

        //如果系统开启了多租户开关，则添加租户的临时缓存
        if (ConstantContextHolder.getTenantOpenFlag()) {
            authService.cacheTenantInfo(tenantCode);
        }

        String token = authService.login(account, password);
        return new SuccessResponseData(token);
    }

    /**
     * 退出登录
     *
     * @author xuyuxiang
     * @date 2020/3/16 15:02
     */
    @GetMapping("/logout")
    public void logout() {
        authService.logout();
    }

    /**
     * 获取当前登录用户信息
     *
     * @author xuyuxiang, fengshuonan
     * @date 2020/3/23 17:57
     */
    @GetMapping("/getLoginUser")
    public ResponseData getLoginUser() {
        return new SuccessResponseData(LoginContextHolder.me().getSysLoginUserUpToDate());
    }

    @PostMapping("/getLogin")
    public ResponseData getLogin(@RequestBody Map map) {
        String keyText = map.get("reqCont").toString();

        String decrypt = null;
        try {
            if (keyText!=null){
                final String s = keyText.replaceAll(" ", "+");
                decrypt = DESUtil.decrypt(s);
            }else{
                log.error(keyText+":解密失败");
                return new ErrorResponseData(500,"解密失败");
            }
        } catch (Exception e) {
            //加密失败
            log.error(keyText+":解密失败", e);
            return new ErrorResponseData(500,"解密失败");
        }
        log.info(keyText+":解密privateDecryptUser：" + decrypt);
        Dict dict = JSONObject.parseObject(decrypt, Dict.class);

        return this.login(dict);
    }

    //用户加密
    @PostMapping("/user/encrypt")
    public ResponseData encrypt(@RequestBody Dict dict) throws Exception {
        String encryptJson = JSONObject.toJSONString(dict);
        String s = encryptJson.replaceAll("\t", "").replaceAll("\n", "");
        String encrypt = DESUtil.encrypt(s);
        return new SuccessResponseData(encrypt);
    }

}
